<template>
  <view class="memo-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <uni-search-bar placeholder="搜索备忘录" radius="100" @confirm="searchMemo"></uni-search-bar>
      <button class="add-btn" @click="addNewMemo">
        <uni-icons type="plusempty" size="20" color="#fff"></uni-icons>
      </button>
    </view>
    
    <!-- 备忘录列表 -->
    <scroll-view class="memo-list" scroll-y>
      <!-- 按日期分组 -->
      <view v-for="(group, date) in groupedMemos" :key="date" class="date-group">
        <view class="date-header">{{date}}</view>
        
        <!-- 单个备忘录项 -->
        <view v-for="memo in group" :key="memo.id" class="memo-item" @click="editMemo(memo.id)">
          <!-- 左侧标记和内容 -->
          <view class="memo-left">
            <view class="priority-marker" :class="'priority-' + memo.priority"></view>
            <view class="memo-content">
              <view class="memo-title">{{memo.title}}</view>
              <view class="memo-desc">{{memo.content}}</view>
              
              <!-- 附加信息 -->
              <view class="memo-meta" v-if="memo.dueDate || memo.location">
                <view class="meta-item" v-if="memo.dueDate">
                  <uni-icons type="calendar" size="14" color="#999"></uni-icons>
                  <text>{{memo.dueDate}} {{memo.dueTime}}</text>
                  <uni-icons v-if="memo.hasReminder" type="notification" size="14" color="#ff5a5f"></uni-icons>
                </view>
                <view class="meta-item" v-if="memo.location">
                  <uni-icons type="location" size="14" color="#999"></uni-icons>
                  <text>{{memo.location}}</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 右侧操作按钮 -->
          <view class="memo-right">
            <button class="action-btn" @click.stop="toggleComplete(memo.id)">
              <uni-icons :type="memo.completed ? 'checkbox-filled' : 'circle'" 
                        :color="memo.completed ? '#4cd964' : '#ddd'"></uni-icons>
            </button>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 添加/编辑备忘录的弹窗 -->
    <uni-popup ref="memoPopup" type="bottom">
      <view class="memo-edit">
        <view class="edit-header">
          <text>{{isEditing ? '编辑备忘录' : '新建备忘录'}}</text>
          <view class="header-actions">
            <button v-if="isEditing" class="delete-btn" @click="deleteMemo">
              <uni-icons type="trash" size="20" color="#ff5a5f"></uni-icons>
            </button>
            <button @click="closePopup">取消</button>
          </view>
        </view>
        
        <view class="edit-form">
          <input class="title-input" v-model="currentMemo.title" placeholder="标题" />
          <textarea class="content-input" v-model="currentMemo.content" placeholder="内容"></textarea>
          
          <view class="form-row">
            <picker mode="date" @change="setDueDate">
              <view class="picker">
                <uni-icons type="calendar" size="18" color="#666"></uni-icons>
                <text>{{currentMemo.dueDate || '截止日期'}}</text>
              </view>
            </picker>
            
            <picker mode="time" @change="setDueTime">
              <view class="picker">
                <uni-icons type="time" size="18" color="#666"></uni-icons>
                <text>{{currentMemo.dueTime || '时间'}}</text>
              </view>
            </picker>
          </view>
          
          <view class="form-row">
            <picker @change="setLocation">
              <view class="picker">
                <uni-icons type="location" size="18" color="#666"></uni-icons>
                <text>{{currentMemo.location || '地点 (可选)'}}</text>
              </view>
            </picker>
          </view>
          
          <view class="form-row">
            <text>优先级</text>
            <view class="priority-options">
              <view v-for="level in 3" :key="level" 
                    @click="setPriority(level)"
                    :class="['priority-option', 'priority-' + level, 
                             {active: currentMemo.priority === level}]">
                {{['低', '中', '高'][level-1]}}
              </view>
            </view>
          </view>
          
          <view class="form-row reminder-option">
            <switch :checked="currentMemo.hasReminder" @change="toggleReminder" />
            <text>设置提醒</text>
          </view>
          
          <button class="save-btn" @click="saveMemo">{{isEditing ? '保存' : '添加'}}</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isEditing: false,
      currentMemo: {
        id: '',
        title: '',
        content: '',
        dueDate: '',
        dueTime: '',
        location: '',
        priority: 1,
        hasReminder: false,
        completed: false,
        createdAt: ''
		 
      },
	  memos:[],
      searchText: ''
    }
  },
  computed: {
    filteredMemos() {
      if (!this.searchText) {
        return this.memos;
      }
      const searchTextLower = this.searchText.toLowerCase();
      return this.memos.filter(memo => 
        memo.title.toLowerCase().includes(searchTextLower) || 
        memo.content.toLowerCase().includes(searchTextLower)
      );
    },
    groupedMemos() {
      // 按日期分组并排序
      const groups = {}
      const sortedMemos = [...this.filteredMemos].sort((a, b) => {
        // 未完成的优先，然后按创建时间倒序
        if (a.completed !== b.completed) {
          return a.completed ? 1 : -1
        }
        return new Date(b.createdAt) - new Date(a.createdAt)
      })
      
      sortedMemos.forEach(memo => {
        const date = memo.dueDate || memo.createdAt.split(' ')[0]
        const displayDate = this.formatDate(date)
        
        if (!groups[displayDate]) {
          groups[displayDate] = []
        }
        groups[displayDate].push(memo)
      })
      
      return groups
    }
  },
  methods: {
	  // 从本地存储加载备忘录
	      loadMemos() {
	        const savedMemos = uni.getStorageSync('memos');
	        if (savedMemos && savedMemos.length > 0) {
	          this.memos = savedMemos;
	        } else {
	          // 如果没有保存的数据，使用默认示例数据
	          this.memos = [
	                   {
	                     id: '1',
	                     title: '完成项目提案',
	                     content: '准备下周会议要用的项目提案文档',
	                     dueDate: '2023-06-15',
	                     dueTime: '18:00',
	                     location: '公司',
	                     priority: 3,
	                     hasReminder: true,
	                     completed: false,
	                     createdAt: '2023-06-10 09:30'
	                   },
	                   {
	                     id: '2',
	                     title: '购买生日礼物',
	                     content: '为朋友挑选生日礼物',
	                     dueDate: '2023-06-12',
	                     dueTime: '',
	                     location: '购物中心',
	                     priority: 2,
	                     hasReminder: false,
	                     completed: false,
	                     createdAt: '2023-06-08 15:20'
	                   },
	                   {
	                     id: '3',
	                     title: '阅读新书',
	                     content: '完成《设计心理学》第5章',
	                     dueDate: '',
	                     dueTime: '',
	                     location: '家',
	                     priority: 1,
	                     hasReminder: false,
	                     completed: true,
	                     createdAt: '2023-06-05 20:15'
	                   }
	                 ];
	                 this.saveMemos();
	               }
	             },
    formatDate(dateStr) {
          const date = new Date(dateStr)
          const today = new Date()
          const tomorrow = new Date(today)
          tomorrow.setDate(tomorrow.getDate() + 1)
          
          if (date.toDateString() === today.toDateString()) {
            return '今天'
          } else if (date.toDateString() === tomorrow.toDateString()) {
            return '明天'
          } else {
            return `${date.getMonth() + 1}月${date.getDate()}日`
          }
        },
        searchMemo(e) {
          this.searchText = e.value
        },
        addNewMemo() {
          this.isEditing = false
          this.currentMemo = {
            id: Date.now().toString(),
            title: '',
            content: '',
            dueDate: '',
            dueTime: '',
            location: '',
            priority: 1,
            hasReminder: false,
            completed: false,
            createdAt: new Date().toISOString()
          }
          this.$refs.memoPopup.open()
        },
        deleteMemo() {
          uni.showModal({
            title: '确认删除',
            content: '确定要删除这个备忘录吗？',
            success: (res) => {
              if (res.confirm) {
                const index = this.memos.findIndex(m => m.id === this.currentMemo.id)
                if (index !== -1) {
                  this.memos.splice(index, 1)
                  this.saveMemos(); // 保存更改
                  this.$refs.memoPopup.close()
                  uni.showToast({
                    title: '删除成功',
                    icon: 'success'
                  })
                }
              }
            }
          })
        },
        editMemo(id) {
          const memo = this.memos.find(m => m.id === id)
          if (memo) {
            this.isEditing = true
            this.currentMemo = {...memo}
            this.$refs.memoPopup.open()
          }
        },
        closePopup() {
          this.$refs.memoPopup.close()
        },
        setDueDate(e) {
          this.currentMemo.dueDate = e.detail.value
        },
        setDueTime(e) {
          this.currentMemo.dueTime = e.detail.value
        },
        setLocation(e) {
          this.currentMemo.location = e.detail.value
        },
        setPriority(level) {
          this.currentMemo.priority = level
        },
        toggleReminder(e) {
          this.currentMemo.hasReminder = e.detail.value
        },
        saveMemos() {
          uni.setStorageSync('memos', this.memos);
        },
        saveMemo() {
          if (this.isEditing) {
            const index = this.memos.findIndex(m => m.id === this.currentMemo.id);
            if (index !== -1) {
              this.memos.splice(index, 1, this.currentMemo);
            }
          } else {
            this.memos.unshift(this.currentMemo);
          }
          this.saveMemos(); // 保存到本地存储
          this.$refs.memoPopup.close();
        },
        toggleComplete(id) {
          const memo = this.memos.find(m => m.id === id);
          if (memo) {
            memo.completed = !memo.completed;
            if (memo.completed) {
              memo.completedAt = new Date().toISOString();
            } else {
              memo.completedAt = '';
            }
            this.saveMemos(); // 保存更改
          }
        }
      },
      onShow() {
        // 从本地存储加载数据
        this.loadMemos();
      }
    }
</script>

<style lang="scss" scoped>
.memo-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--neutral-light);
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: var(--neutral-white);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
   transition: box-shadow 0.3s ease; /* 添加过渡动画 */
  
  .add-btn {
    width: 36px;
    height: 36px;
    margin-left: 10px;
    border-radius: 50%;
    background-color: var(--primary-morandi);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0;
    transition: background-color 0.3s;
    
    &:active {
      background-color: var(--primary-morandi-active);
    }
  }
}

.memo-list {
  flex: 1;
  padding: 10px 15px;
  background-color: var(--neutral-light);
}

.date-group {
  margin-bottom: 20px;
  
  .date-header {
    font-size: var(--font-size-sm);
    color: var(--neutral-dark);
    padding: 8px 0;
    border-bottom: 1px solid var(--neutral-medium);
    margin-bottom: 10px;
  }
}

.memo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: var(--neutral-white);
  border-radius: 8px;
  padding: 12px 15px;
  margin-bottom: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
  position: relative;
  overflow: hidden;
  
  &:active {
    transform: translateY(2px);
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
  }
  
  .swipe-actions {
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    display: flex;
    
    .action {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 20px;
      color: white;
      
      &.edit {
        background-color: var(--secondary-yellow);
      }
      
      &.delete {
        background-color: var(--secondary-purple);
      }
    }
  }
  
  .memo-left {
    display: flex;
    flex: 1;
    overflow: hidden;
    
    .priority-marker {
      width: 4px;
      height: 40px;
      margin-right: 12px;
      border-radius: 2px;
      
      &.priority-1 { background-color: var(--secondary-blue); }
      &.priority-2 { background-color: var(--secondary-yellow); }
      &.priority-3 { background-color: var(--secondary-purple); }
    }
    
    .memo-content {
      flex: 1;
      overflow: hidden;
      
      .memo-title {
        font-size: var(--font-size-base);
        font-weight: var(--font-weight-bold);
        margin-bottom: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: var(--neutral-black);
      }
      
      .memo-desc {
        font-size: var(--font-size-sm);
        color: var(--neutral-dark);
        margin-bottom: 6px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .memo-meta {
        display: flex;
        flex-direction: column;
        gap: 4px;
        
        .meta-item {
          display: flex;
          align-items: center;
          font-size: var(--font-size-xs);
          color: var(--neutral-medium);
          
          text {
            margin-left: 4px;
          }
          
          .uni-icons {
            margin-right: 4px;
          }
        }
      }
    }
  }
  
  .memo-right {
    margin-left: 10px;
    
    .action-btn {
      padding: 8px;
      background: transparent;
      border: none;
      font-size: 20px;
      color: var(--neutral-medium);
      
      &:active {
        color: var(--primary-morandi);
      }
    }
  }
}

.memo-edit {
  background-color: var(--neutral-white);
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  padding: 20px;
  
 .edit-header {
   display: flex;
   justify-content: space-between;
   align-items: center;
   margin-bottom: 20px;
   font-size: var(--font-size-lg);
   font-weight: var(--font-weight-bold);
   color: var(--neutral-black);
   
   .header-actions {
     display: flex;
     align-items: center;
     gap: 12px;
     
     /* 统一按钮样式 */
     button, .delete-btn {
       display: flex;
       align-items: center;
       justify-content: center;
       height: 36px;
       padding: 0 10px;
       background: transparent;
       border: none;
       color: var(--primary-morandi);
       font-size: var(--font-size-base);
       font-weight: var(--font-weight-normal);
       border-radius: 4px;
       transition: all 0.2s;
     }
     
     .delete-btn {
       width: 36px;
       padding: 0;
       color: var(--secondary-purple);
       
       &:active {
         opacity: 0.7;
         transform: scale(0.95);
       }
     }
   }
 }
  
  .edit-form {
    display: flex;
    flex-direction: column;
    
    .title-input {
      font-size: var(--font-size-lg);
      font-weight: var(--font-weight-bold);
      padding: 8px 0;
      margin-bottom: 15px;
      border-bottom: 1px solid var(--neutral-light);
      color: var(--neutral-black);
    }
    
    .content-input {
      height: 100px;
      font-size: var(--font-size-base);
      margin-bottom: 20px;
      padding: 8px 0;
      color: var(--neutral-dark);
    }
    
    .form-row {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      color: var(--neutral-dark);
      
      .picker {
        display: flex;
        align-items: center;
        padding: 8px 12px;
        background-color: var(--neutral-light);
        border-radius: 6px;
        margin-right: 10px;
        
        text {
          margin-left: 6px;
          font-size: var(--font-size-sm);
          color: var(--neutral-dark);
        }
      }
    }
    
    .priority-options {
      display: flex;
      margin-left: 15px;
      
      .priority-option {
        padding: 4px 12px;
        margin-right: 8px;
        border-radius: 4px;
        font-size: var(--font-size-sm);
        cursor: pointer;
        transition: all 0.2s;
        
        &.priority-1 {
          background-color: #f0f8ff;
          color: var(--secondary-blue);
          border: 1px solid var(--secondary-blue);
        }
        
        &.priority-2 {
          background-color: #fff8f0;
          color: var(--secondary-yellow);
          border: 1px solid var(--secondary-yellow);
        }
        
        &.priority-3 {
          background-color: #fff0f0;
          color: var(--secondary-purple);
          border: 1px solid var(--secondary-purple);
        }
        
        &.active {
          color: var(--neutral-white);
          border: none;
          
          &.priority-1 {
            background-color: var(--secondary-blue);
          }
          
          &.priority-2 {
            background-color: var(--secondary-yellow);
          }
          
          &.priority-3 {
            background-color: var(--secondary-purple);
          }
        }
      }
    }
    
    .reminder-option {
      justify-content: space-between;
      padding: 10px 0;
      border-top: 1px solid var(--neutral-light);
      border-bottom: 1px solid var(--neutral-light);
      margin-top: 10px;
    }
    
    .save-btn {
      margin-top: 20px;
      background-color: var(--primary-morandi);
      color: var(--neutral-white);
      border-radius: 8px;
      padding: 12px;
      font-size: var(--font-size-base);
      font-weight: var(--font-weight-bold);
      border: none;
      transition: background-color 0.3s;
      
      &:active {
        background-color: var(--primary-morandi-active);
      }
    }
  }
}

/* 已完成备忘录的样式 */
.memo-item.completed {
  opacity: 0.7;
  
  .memo-title, .memo-desc {
    text-decoration: line-through;
    color: var(--neutral-medium) !important;
  }
}
</style>